<template>
	<view class="chapter-container">
		<!-- 章节标题 -->
		<view class="chapter-header">
			<text class="course-title">{{ chapterInfo.courseTitle }}</text>
			<text class="chapter-title">第{{ chapterInfo.index }}章 {{ chapterInfo.title }}</text>
			<text class="study-duration">已学习 {{ Math.floor(watchDuration/60) }}分{{ watchDuration%60 }}秒</text>
		</view>
		
		<!-- 章节内容 -->
		<scroll-view class="chapter-content" scroll-y="true">
			<rich-text :nodes="chapterInfo.content"></rich-text>
		</scroll-view>
		
		<!-- AI悬浮按钮 -->
		<view class="ai-float-btn" @tap="showAIModal">
			<text class="icon">🤖</text>
		</view>

		<!-- AI对话弹窗 -->
		<view class="ai-modal" v-if="showModal">
			<view class="modal-mask" @tap="closeAIModal"></view>
			<view class="ai-popup">
				<view class="popup-header">
					<text class="title">AI 助手</text>
					<text class="close" @tap="closeAIModal">×</text>
				</view>

				<scroll-view 
					class="chat-content" 
					scroll-y 
					:scroll-top="scrollTop"
				>
					<view class="chat-list">
						<view class="chat-item" v-for="(item, index) in chatList" :key="index">
							<view class="chat-item-content">
								<view :class="['message', item.type]">
									<view v-if="item.type === 'loading'" class="loading-dots">
										<text class="dot"></text>
										<text class="dot"></text>
										<text class="dot"></text>
									</view>
									<template v-else>{{ item.content }}</template>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>

				<view class="popup-footer">
					<view class="input-area">
						<input 
							class="message-input"
							v-model="inputMessage"
							placeholder="请输入您的问题"
							:disabled="loading"
							@confirm="handleSend"
						/>
						<button 
							class="send-btn" 
							@tap="handleSend"
							:disabled="!inputMessage.trim() || loading"
						>
							{{ loading ? '思考中...' : '发送' }}
						</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { courseApi } from '@/utils/api'
import request from '@/utils/request'

const chapterInfo = ref({})
const totalChapters = ref(0)
const courseId = ref(null)
const showModal = ref(false)
const loading = ref(false)
const chatList = ref([])
const scrollTop = ref(0)
const inputMessage = ref('')
const startTime = ref(0)
const watchDuration = ref(0)
const timer = ref(null)

onMounted(() => {
	// 获取路由参数
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const options = currentPage.$page.options
	
	// 获取课程ID
	courseId.value = options.id
	
	// 获取章节信息
	const info = uni.getStorageSync('currentChapter')
	if (info) {
		chapterInfo.value = info
		// 从课程详情中获取总章节数
		const courseDetail = uni.getStorageSync('currentCourse')
		if (courseDetail && courseDetail.chapters) {
			totalChapters.value = courseDetail.chapters.length
		} else {
			totalChapters.value = 3 // 默认值
		}
	} else {
		// 如果没有章节信息，返回上一页
		uni.showToast({
			title: '章节信息不存在',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	}
	
	// 开始计时
	startTime.value = Date.now()
	timer.value = setInterval(() => {
		watchDuration.value = Math.floor((Date.now() - startTime.value) / 1000)
	}, 1000)
})

// 在组件销毁前记录观看时长
onBeforeUnmount(() => {
	if (timer.value) {
		clearInterval(timer.value)
		saveWatchRecord()
	}
})

// 保存观看记录
const saveWatchRecord = async () => {
	try {
		const res = await request({
			url: '/api/course/watch/record',
			method: 'POST',
			data: {
				courseId: Number(courseId.value),
				chapterId: Number(chapterInfo.value.id),
				duration: Number(watchDuration.value)
			}
		})
		
		if (res.code === 0) {
			console.log('观看记录保存成功')
		} else {
			throw new Error(res.message || '保存观看记录失败')
		}
	} catch (error) {
		console.error('保存观看记录失败:', error)
		uni.showToast({
			title: error.message || '保存记录失败',
			icon: 'none'
		})
	}
}

// 显示AI弹窗
const showAIModal = () => {
	showModal.value = true
}

// 关闭AI弹窗
const closeAIModal = () => {
	showModal.value = false
}

// 修改发送消息的处理
const handleSend = async () => {
	const message = inputMessage.value.trim()
	if (!message || loading.value) return
	
	loading.value = true
	
	try {
		// 添加用户消息
		chatList.value.push({
			type: 'user',
			content: message
		})
		
		// 添加 loading 消息
		chatList.value.push({
			type: 'loading'
		})
		
		// 清空输入框
		inputMessage.value = ''
		
		// 滚动到底部
		scrollToBottom()
		
		const res = await request({
			url: '/api/AI',
			method: 'POST',
			data: {
				message,
				chapterId: chapterInfo.value.id
			}
		})
		
		// 移除 loading 消息
		chatList.value.pop()
		
		if (res.code === 0) {
			// 添加AI回复
			chatList.value.push({
				type: 'ai',
				content: res.data.aimessage
			})
			// 滚动到底部
			scrollToBottom()
		} else {
			throw new Error(res.message || '请求失败')
		}
	} catch (error) {
		// 移除 loading 消息
		chatList.value.pop()
		console.error('发送消息失败:', error)
		uni.showToast({
			title: error.message || '发送失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 滚动到底部
const scrollToBottom = () => {
	setTimeout(() => {
		scrollTop.value = 9999
	}, 100)
}
</script>

<style scoped>
.chapter-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #fff;
}

.chapter-header {
	padding: 30rpx;
	background: linear-gradient(135deg, #007aff 0%, #0056b3 100%);
	color: #fff;
}

.course-title {
	font-size: 24rpx;
	opacity: 0.8;
	display: block;
	margin-bottom: 10rpx;
}

.chapter-title {
	font-size: 32rpx;
	font-weight: bold;
}

.chapter-content {
	flex: 1;
	padding: 30rpx;
	font-size: 28rpx;
	line-height: 1.8;
	color: #333;
	overflow-x: hidden;
	box-sizing: border-box;
	width: 100%;
}

.bottom-nav {
	display: flex;
	padding: 20rpx;
	border-top: 1rpx solid #eee;
}

.nav-btn {
	flex: 1;
	height: 80rpx;
	line-height: 80rpx;
	margin: 0 10rpx;
	background: linear-gradient(135deg, #007aff 0%, #0056b3 100%);
	color: #fff;
	font-size: 28rpx;
	border-radius: 40rpx;
}

.nav-btn[disabled] {
	background: #ccc;
	opacity: 0.8;
}

.ai-float-btn {
	position: fixed;
	right: 30rpx;
	bottom: 100rpx;
	width: 100rpx;
	height: 100rpx;
	background: linear-gradient(135deg, #007aff 0%, #0056b3 100%);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 16rpx rgba(0, 122, 255, 0.3);
	z-index: 99;
}

.ai-float-btn .icon {
	font-size: 48rpx;
}

.ai-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.modal-mask {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
}

.ai-popup {
	position: relative;
	width: 80%;
	max-width: 600rpx;
	background-color: #fff;
	border-radius: 24rpx;
	overflow: hidden;
	z-index: 1000;
}

.popup-header {
	padding: 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 2rpx solid #f5f5f5;
}

.title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.close {
	font-size: 48rpx;
	color: #999;
	padding: 20rpx;
}

.chat-content {
	height: 60vh;
	max-height: 800rpx;
}

.chat-list {
	padding: 30rpx;
}

.chat-item {
	margin-bottom: 30rpx;
}

.chat-item-content {
	display: flex;
	padding: 0 20rpx;
}

.message {
	max-width: 70%;
	padding: 20rpx 24rpx;
	border-radius: 20rpx;
	font-size: 28rpx;
	line-height: 1.6;
	word-break: break-all;
	white-space: pre-wrap;
}

.user {
	background-color: #007aff;
	color: #fff;
	margin-left: auto;  /* 用户消息靠右 */
	border-top-right-radius: 20rpx;
	border-top-left-radius: 20rpx;
	border-bottom-left-radius: 20rpx;
	border-bottom-right-radius: 4rpx;
}

.ai {
	background-color: #f5f7fa;
	color: #333;
	margin-right: auto;  /* AI消息靠左 */
	border-top-right-radius: 20rpx;
	border-top-left-radius: 20rpx;
	border-bottom-right-radius: 20rpx;
	border-bottom-left-radius: 4rpx;
}

.input-area {
	display: flex;
	align-items: center;
	gap: 16rpx;
	padding: 20rpx 30rpx;
	border-top: 2rpx solid #f5f5f5;
	background-color: #fff;
}

.message-input {
	flex: 1;
	height: 72rpx;
	background-color: #f5f7fa;
	border-radius: 36rpx;
	padding: 0 30rpx;
	font-size: 28rpx;
}

.send-btn {
	min-width: 120rpx;
	height: 72rpx;
	line-height: 72rpx;
	background: #007aff;
	color: #fff;
	font-size: 28rpx;
	border-radius: 36rpx;
	padding: 0 30rpx;
	margin: 0;
}

.popup-footer {
	padding: 30rpx;
	border-top: 2rpx solid #f5f5f5;
}

/* 优化动画 */
.ai-popup {
	animation: popIn 0.2s ease-out;
}

@keyframes popIn {
	from {
		opacity: 0;
		transform: scale(0.9);
	}
	to {
		opacity: 1;
		transform: scale(1);
	}
}

/* 添加 loading 样式 */
.loading-dots {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.dot {
	width: 12rpx;
	height: 12rpx;
	background-color: #666;
	border-radius: 50%;
	display: inline-block;
	animation: dotBounce 1.4s infinite ease-in-out;
}

.dot:nth-child(1) {
	animation-delay: 0s;
}

.dot:nth-child(2) {
	animation-delay: 0.16s;
}

.dot:nth-child(3) {
	animation-delay: 0.32s;
}

@keyframes dotBounce {
	0%, 80%, 100% {
		transform: scale(0);
		opacity: 0.2;
	}
	40% {
		transform: scale(1);
		opacity: 1;
	}
}

/* 调整 loading 消息的样式 */
.loading {
	background-color: #f5f7fa;
	color: #333;
	margin-right: auto;
	border-top-right-radius: 20rpx;
	border-top-left-radius: 20rpx;
	border-bottom-right-radius: 20rpx;
	border-bottom-left-radius: 4rpx;
	min-width: 100rpx;
}

/* 富文本内容样式 */
:deep(.rich-text) {
	width: 100% !important;
	overflow-x: hidden;
}

/* 处理所有富文本内的元素 */
:deep(.rich-text) * {
	max-width: 100% !important;
	box-sizing: border-box !important;
	white-space: normal !important;
	word-break: break-word !important;
}

/* 处理图片 */
:deep(.rich-text) img {
	display: block !important;
	max-width: 100% !important;
	width: 100% !important;
	height: auto !important;
	margin: 0 auto;
}

/* 处理表格 */
:deep(.rich-text) table {
	width: 100% !important;
	table-layout: fixed !important;
	margin: 0 !important;
	padding: 0 !important;
}

:deep(.rich-text) td,
:deep(.rich-text) th {
	word-break: break-all !important;
	word-wrap: break-word !important;
	white-space: normal !important;
	padding: 5rpx !important;
}

/* 处理代码块 */
:deep(.rich-text) pre,
:deep(.rich-text) code {
	white-space: pre-wrap !important;
	word-wrap: break-word !important;
	overflow-x: hidden !important;
	width: 100% !important;
	box-sizing: border-box !important;
	padding: 10rpx !important;
}

/* #ifdef MP-WEIXIN */
/* 小程序特殊处理 */
.chapter-content {
	padding: 20rpx !important;
}

:deep(.rich-text) {
	width: 100% !important;
	box-sizing: border-box !important;
}

:deep(.rich-text) view {
	width: 100% !important;
	overflow-x: hidden !important;
}
/* #endif */

/* 添加学习时长样式 */
.study-duration {
	font-size: 24rpx;
	color: rgba(255,255,255,0.8);
	margin-top: 10rpx;
	display: block;
}
</style> 